package com.kun.enums;

import cn.hutool.core.util.StrUtil;
import com.kun.db.dialect.DriverNamePool;
import com.kun.entity.KunDatasource;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * 支持的数据源类型
 *
 * @author kun.li
 */
@Getter
@RequiredArgsConstructor
public enum DsTypeEnums {

    MYSQL("mysql", "mysql数据源", DriverNamePool.DRIVER_MYSQL_V6,
            "jdbc:mysql://{host}:{port}/{dsDataBase}?remarks=true"),
    ORACLE("oracle", "oracle数据源", DriverNamePool.DRIVER_ORACLE,
            "jdbc:oracle:thin:@{host}:{port}/{dsDataBase}?remarks=true"),
    SQLSERVER("sqlserver", "sqlserver数据源", DriverNamePool.DRIVER_SQLSERVER,
            "jdbc:sqlserver://{host}:{port};databaseName={dsDataBase}?remarks=true"),
    DB2("db2", "db2数据源", DriverNamePool.DRIVER_DB2,
            "jdbc:db2://{host}:{port}/{dsDataBase}:currentSchema={dsSchema}"),
    ;

    private final String dsType;

    private final String describe;

    private final String driverClassName;
    private final String driverUri;

    /**
     * 获取所有支持的数据源类型
     */
    public static List<String> dsTypeList() {
        List<String> dsTypeList = new ArrayList<>();
        for (DsTypeEnums dsTypeEnums : values()) {
            dsTypeList.add(dsTypeEnums.getDsType());
        }
        return dsTypeList;
    }

    public static String getDriverClassName(String dsType) {
        for (DsTypeEnums dsTypeEnums : values()) {
            if (dsType.equals(dsTypeEnums.getDsType())) {
                return dsTypeEnums.getDriverClassName();
            }
        }
        return null;
    }

    public static String buildDriverUrl(KunDatasource kunDatasource) {
        for (DsTypeEnums dsTypeEnums : values()) {
            if (kunDatasource.getDsType().equals(dsTypeEnums.getDsType())) {
                return buildDriverUri(dsTypeEnums.getDriverUri(), kunDatasource);
            }
        }
        return null;
    }

    private static String buildDriverUri(String driverUriTemplate, KunDatasource kunDatasource) {
        Properties properties = new Properties();
        properties.put("host", kunDatasource.getHost());
        properties.put("port", kunDatasource.getPort());
        properties.put("dsDataBase", kunDatasource.getDsDataBase());
        String dsSchema = kunDatasource.getDsSchema();
        if (StrUtil.isNotEmpty(dsSchema)) {
            properties.put("dsSchema", dsSchema);
        }
        String driverUri = StrUtil.format(driverUriTemplate, properties);
        String extendProperties = kunDatasource.getDriverUrlExtendProperties();
        if (StrUtil.isNotEmpty(extendProperties)) {
            if (driverUri.contains("?")) {
                driverUri = driverUri + "&" + extendProperties;
            } else {
                driverUri = driverUri + "?" + extendProperties;
            }
        }
        return driverUri;

    }


}
